﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace Boco.CommonLib
{
    public static class XmlNodeExtensions
    {
        /// <summary>
        /// 获取属性
        /// </summary>
        /// <param name="node"></param>
        /// <param name="attName">属性名</param>
        /// <returns></returns>
        public static string GetAttribute(this XmlNode node, string attName)
        {
            string rtn = string.Empty;
            if (node != null)
            {
                var value = node.Attributes[attName];
                if (value != null)
                {
                    rtn = value.Value;
                }
            }

            return rtn;
        }

        /// <summary>
        /// 获取属性并转化为整型
        /// </summary>
        /// <param name="node"></param>
        /// <param name="attName"></param>
        /// <returns></returns>
        public static int GetAttributesAsInt(this XmlNode node, string attName)
        {
            string value = node.GetAttribute(attName);
            if (string.IsNullOrEmpty(value))
            {
                return default(int);
            }
            else
            {
                return int.Parse(value);
            }
        }

        public static bool GetAttributesAsBool(this XmlNode node, string attName)
        {
            string value = node.GetAttribute(attName);
            if (string.IsNullOrEmpty(value))
            {
                return false;
            }
            else
            {
                return attName.ToUpper() == "TRUE" ? true : false;
            }
        }

        /// <summary>
        /// 获取属性
        /// </summary>
        /// <param name="node"></param>
        /// <param name="attName">属性名</param>
        /// <returns></returns>
        public static string GetAttribute(this XElement node, string attName)
        {
            string rtn = string.Empty;
            if (node != null)
            {
                var value = node.Attribute(attName);
                if (value != null)
                {
                    rtn = value.Value;
                }
            }

            return rtn;
        }

        public static int GetAttributesAsInt(this XElement node, string attName)
        {
            string value = node.GetAttribute(attName);
            if (string.IsNullOrEmpty(value))
            {
                return default(int);
            }
            else
            {
                return int.Parse(value);
            }
        }


        public static bool GetAttributesAsBool(this XElement node, string attName)
        {
            string value = node.GetAttribute(attName);
            if (string.IsNullOrEmpty(value))
            {
                return false;
            }
            else
            {
                return value.ToUpper() == "TRUE";
            }
        }
    }
}
